package homework;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-01-06
 * Time: 15:14
 */
//https://leetcode.cn/problems/min-stack/submissions/393374613/
class MinStack {
    //使用两个栈，其中一个不断入栈，一个存储最小值
    private Stack<Integer> stack;
    private Stack<Integer> minStack;

    public MinStack() {
        stack = new Stack<>();
        minStack = new Stack<>();
    }

    public void push(int val) {
        stack.push(val);
        if (minStack.empty()) {
            minStack.push(val);
        } else {
            if (stack.peek() <= minStack.peek()) {
                minStack.push(val);
            }
        }
    }

    public void pop() {
        if (!stack.empty()) {
            int val = stack.pop();
            //minStack的栈顶元素若与val相等，则一同出栈
            if (val == minStack.peek()) {
                minStack.pop();
            }
        }
    }

    public int top() {
        if (!stack.empty()) {
            return stack.peek();
        }
        return -1;
    }

    public int getMin() {
        return minStack.peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(val);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */


class MinStack1 {
    private Deque<Integer> stack;
    private Deque<Integer> minStack;
    public MinStack1() {
        stack = new LinkedList<>();
        minStack = new LinkedList<>();
        minStack.push(Integer.MAX_VALUE);
    }

    public void push(int val) {
        stack.push(val);
        minStack.push(Math.min(minStack.peek(), val));
        //两个栈的元素个数相同，minStack重复入最小值
        //保证pop()的同步
    }

    public void pop() {
        stack.pop();
        minStack.pop();
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return minStack.peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(val);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */